import { PLAY_MODE } from "@/assets/js/constant";
import { shuffle } from "@/assets/js/util";
export function selectPlay({commit}, {list, index}) {
  commit('setPlayMode', PLAY_MODE.sequence)
  commit('setSquenceList', list)
  commit('setPlayingState', true)
  commit('setFullScreen', true)
  commit('setPlaylist', list)
  commit("setCurrentIndex", index)
}

export function randomPlay ({commit}, list) {
  commit('setPlayMode', PLAY_MODE.random)
  commit('setSquenceList', list)
  commit('setPlayingState', true)
  commit('setFullScreen', true)
  commit('setPlaylist', shuffle(list))
  commit("setCurrentIndex", 0)
}

export function changeMode({ commit, state, getters }, mode) {
  const currentId = getters.currentSong.id
  if (mode === PLAY_MODE.random) {
    commit('setPlaylist', shuffle(state.sequenceList))
  } else {
    commit('setPlaylist', state.sequenceList)
  }
  const index = state.playList.findIndex((song) => {
    return song.id === currentId
  })
  commit('setCurrentIndex', index)
  commit('setPlayMode', mode)
}

export function removeSong({commit, state}, song) {
  const sequenceList = state.sequenceList.slice()
  const playList = state.playList.slice()
  let currentIndex = state.currentIndex

  const sequenceIndex = findIndex(sequenceList, song)
  const playIndex = findIndex(playList, song)
  if (playIndex < 0 || sequenceIndex < 0) return
  sequenceList.splice(sequenceIndex, 1)
  playList.splice(playIndex, 1)

  if (playIndex < currentIndex || currentIndex === playList.length) {
    currentIndex --
  }

  commit('setSquenceList', sequenceList)
  commit('setPlaylist', playList)
  commit('setCurrentIndex', currentIndex)
  if (!playList.length)
 {
   commit('setPlayingState', false)
 }}

export function clearSongList ({commit}) {
  commit('setSquenceList', [])
  commit('setPlaylist', [])
  commit('setCurrentIndex', 0)
  commit('setPlayingState', false)
}

function findIndex (list, song) {
  return list.findIndex((item) => {
    return item.id === song.id
  })
}

export function addSong ({commit, state}, song) {
  const playList = state.playList.slice()
  const sequenceList = state.sequenceList.slice()
  let currentIndex = state.currentIndex
  const playIndex = findIndex(playList, song)

  if (playIndex > -1) {
    currentIndex = playIndex
  } else {
    playList.push(song)
    currentIndex = playList.length - 1
  }
  const sequenceIndex = findIndex(sequenceList, song)
  if (sequenceIndex === -1) {
    sequenceList.push(song)
  }
  commit('setSquenceList', sequenceList)
  commit('setPlaylist', playList)
  commit('setCurrentIndex', currentIndex)
  commit('setPlayingState', true)
  commit('setFullScreen', true)
}